<template>
  <view class="page">
    <!-- 状态栏占位 -->
    <view class="status-bar" :style="{ height: statusBarHeight + 'px' }"></view>

    <!-- 导航栏 -->
    <view class="nav-bar">
      <text class="nav-title">新闻资讯</text>
      <view class="nav-right">
        <view class="nav-icon" @click="onRefresh" :class="{ 'refreshing': isRefreshing }">
          <uni-icons type="refreshempty" size="20" color="#ffffff"></uni-icons>
        </view>
        <view class="nav-icon" @click="showSearch">
          <uni-icons type="search" size="20" color="#ffffff"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 下拉刷新 + 瀑布流列表 -->
    <scroll-view
      class="news-scroll"
      scroll-y
      refresher-enabled
      :refresher-triggered="isRefreshing"
      @refresherrefresh="onRefresh"
      enhanced
      :show-scrollbar="false"
      :enable-back-to-top="true"
      :bounces="true"
      :fast-deceleration="false"
    >
      <!-- 新闻列表 -->
      <view class="news-list">
        <NewsItem
          v-for="news in newsList"
          :key="news.id"
          :news="news"
          @click="goToDetail"
        />

        <!-- 空状态 -->
        <view class="empty-state" v-if="newsList.length === 0 && !isLoading">
          <uni-icons type="info" size="64" color="#ddd"></uni-icons>
          <text class="empty-text">暂无新闻内容</text>
          <button class="refresh-btn" @click="onRefresh">刷新试试</button>
        </view>
      </view>
    </scroll-view>

    <!-- 搜索弹窗 -->
    <uni-popup ref="searchPopup" type="top" :safe-area="false">
      <view class="search-container">
        <view class="search-bar">
          <view class="search-input-wrapper">
            <uni-icons type="search" size="16" color="#999"></uni-icons>
            <input
              v-model="searchKeyword"
              placeholder="搜索新闻..."
              class="search-input"
              @confirm="performSearch"
            />
          </view>
          <text class="search-cancel" @click="hideSearch">取消</text>
        </view>

        <!-- 搜索历史 -->
        <view class="search-history" v-if="searchHistory.length > 0">
          <view class="history-header">
            <text class="history-title">搜索历史</text>
            <text class="history-clear" @click="clearHistory">清空</text>
          </view>
          <view class="history-tags">
            <text
              class="history-tag"
              v-for="keyword in searchHistory"
              :key="keyword"
              @click="searchByKeyword(keyword)"
            >
              {{ keyword }}
            </text>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { newsApi } from '@/api/index.js'
import NewsItem from './components/NewsItem.vue'

// 系统信息
const statusBarHeight = ref(0)

// 新闻列表数据
const newsList = ref([])
const isLoading = ref(false)
const isRefreshing = ref(false)

// 滚动相关 - 使用 scroll-view 的内置功能

// 搜索相关
const searchPopup = ref(null)
const searchKeyword = ref('')
const searchHistory = ref([])
const isSearchMode = ref(false)

// 页面初始化
onMounted(() => {
  // 获取系统信息
  const systemInfo = uni.getSystemInfoSync()
  statusBarHeight.value = systemInfo.statusBarHeight || 0

  // 设置导航栏标题
  uni.setNavigationBarTitle({
    title: '新闻'
  })

  // 加载搜索历史
  loadSearchHistory()

  // 初始加载新闻列表
  loadNewsList()
})

// 加载新闻列表
const loadNewsList = async (keyword = '') => {
  if (isLoading.value) return

  try {
    isLoading.value = true

    const params = {
      page: 0,
      size: 20, // 增加单次加载数量
      sort: 'publishTime,desc'
    }

    if (keyword) {
      params.keyword = keyword
    }

    const response = await newsApi.getNewsList(params)

    if (response.code === 200) {
      newsList.value = response.data.content || []
    } else {
      throw new Error(response.message || '加载失败')
    }
  } catch (error) {
    console.error('加载新闻列表失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    isLoading.value = false
    isRefreshing.value = false
  }
}

// 下拉刷新
const onRefresh = () => {
  isRefreshing.value = true
  loadNewsList(isSearchMode.value ? searchKeyword.value : '')
}





// 跳转到详情页
const goToDetail = (news) => {
  uni.navigateTo({
    url: `/pages/news/detail?id=${news.id}`
  })
}

// 显示搜索
const showSearch = () => {
  searchPopup.value.open()
}

// 隐藏搜索
const hideSearch = () => {
  searchPopup.value.close()
  searchKeyword.value = ''
}

// 执行搜索
const performSearch = () => {
  const keyword = searchKeyword.value.trim()
  if (!keyword) return

  // 保存搜索历史
  saveSearchHistory(keyword)

  // 执行搜索
  isSearchMode.value = true
  loadNewsList(keyword)
  hideSearch()
}

// 通过关键词搜索
const searchByKeyword = (keyword) => {
  searchKeyword.value = keyword
  performSearch()
}

// 加载搜索历史
const loadSearchHistory = () => {
  try {
    const history = uni.getStorageSync('news_search_history')
    if (history) {
      searchHistory.value = JSON.parse(history)
    }
  } catch (error) {
    console.error('加载搜索历史失败:', error)
  }
}

// 保存搜索历史
const saveSearchHistory = (keyword) => {
  try {
    let history = [...searchHistory.value]

    // 移除重复项
    history = history.filter(item => item !== keyword)

    // 添加到开头
    history.unshift(keyword)

    // 限制历史记录数量
    history = history.slice(0, 10)

    searchHistory.value = history
    uni.setStorageSync('news_search_history', JSON.stringify(history))
  } catch (error) {
    console.error('保存搜索历史失败:', error)
  }
}

// 清空搜索历史
const clearHistory = () => {
  searchHistory.value = []
  uni.removeStorageSync('news_search_history')
}
</script>

<style scoped>
.page {
  min-height: 100vh;
  background: linear-gradient(135deg, #e8f5e9 0%, #f1f8e9 100%);
  display: flex;
  flex-direction: column;
}

.status-bar {
  background: #ffffff;
}

.nav-bar {
  height: 88rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 30rpx;
  background: linear-gradient(135deg, #4CAF50 0%, #66BB6A 100%);
  border-bottom: 1rpx solid #f0f0f0;
  box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.2);
}

.nav-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #ffffff;
}

.nav-right {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.nav-icon {
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}

.nav-icon:active {
  background: rgba(0, 0, 0, 0.05);
}

.nav-icon.refreshing {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.news-scroll {
  flex: 1;
  height: 0;
  /* 关键：使用 scroll-view 时不要设置 overflow */
  /* 确保滚动容器能正确处理触摸事件 */
  -webkit-overflow-scrolling: touch;
  /* 防止滚动边界问题 - 在某些情况下可能导致问题，先注释 */
  /* overscroll-behavior: contain; */
  /* 确保触摸事件正常工作 */
  touch-action: manipulation;
  /* 优化渲染性能 */
  transform: translateZ(0);
  will-change: scroll-position;
}

/* scroll-view 内置下拉刷新，不需要自定义指示器 */

.news-list {
  padding: 20rpx 0;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 30rpx;
  padding: 120rpx 0;
}

.empty-text {
  font-size: 28rpx;
  color: #999999;
}

.refresh-btn {
  background: #4CAF50;
  color: #ffffff;
  border: none;
  border-radius: 20rpx;
  padding: 20rpx 40rpx;
  font-size: 28rpx;
}

/* 搜索弹窗样式 */
.search-container {
  background: #ffffff;
  padding-top: var(--status-bar-height);
}

.search-bar {
  display: flex;
  align-items: center;
  gap: 20rpx;
  padding: 20rpx 30rpx;
  border-bottom: 1rpx solid #f0f0f0;
}

.search-input-wrapper {
  flex: 1;
  display: flex;
  align-items: center;
  gap: 16rpx;
  background: #f8f9fa;
  border-radius: 24rpx;
  padding: 16rpx 24rpx;
}

.search-input {
  flex: 1;
  font-size: 28rpx;
  color: #333333;
}

.search-cancel {
  font-size: 28rpx;
  color: #4CAF50;
}

.search-history {
  padding: 30rpx;
}

.history-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20rpx;
}

.history-title {
  font-size: 26rpx;
  color: #666666;
}

.history-clear {
  font-size: 24rpx;
  color: #999999;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.history-tag {
  background: #f8f9fa;
  color: #666666;
  font-size: 24rpx;
  padding: 12rpx 20rpx;
  border-radius: 16rpx;
  border: 1rpx solid #e9ecef;
}
</style>
